import random
import datetime
import uuid
from io import BytesIO
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm
from django.shortcuts import render, HttpResponse,redirect
from utils.tencent.sms import send_sms_single
from django.conf import settings
from django.http.response import JsonResponse
from django_redis import get_redis_connection
from web import models
from utils.Verification_Code import check_code


# Create your views here.

def send_sms(request):
    # 按照老师方法进行重写 入参request传入构造方法中便于钩子函数使用
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        print(form.cleaned_data)
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'errors': form.errors})


"""发送短信
    请求携带不同的短信发送类型
    ?type=login
    ?type=register

    # 我写的方法

    typ = request.GET.get('type')
    phone = request.GET.get('phone')
    template_id = settings.TENCENT_TEMPLATE_ID.get(typ)
    if not template_id:
        return HttpResponse('模板不存在！')
    # 生成四位随机验证码
    code = random.randrange(1000, 9999)
    res = send_sms_single(phone, template_id, [code, ])
    # {'result': 0, 'errmsg': 'OK', 'ext': '', 'sid': '3369:174189097616746571024740286', 'fee': 1, 'isocode': 'CN'}
    if res['result'] == 0:
       
        通过python模块连接redis
        # 连接redis
        conn = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, password=settings.REDIS_PASSWORD,
                           encoding='utf-8')
        # 将phone和code以键值对的形式存入redis，并设置60秒超时（值写入到redis时会自动转字符串）
        conn.set(phone, code, ex=60)
        # 根据键获取值：如果存在获取值（获取到的是字节类型）；不存在则返回None
        value = conn.get(phone)
        print(value.decode())
        
        # 通过django-redis操作redis
        conn = get_redis_connection('default')
        conn.set(phone, code, ex=60)
        value = conn.get(phone)
        print(value.decode())
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'errors': res['errmsg']})
"""


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 将注册数据存储到数据库中，并赋值给instance对象
        instance = form.save()
        # 获取价格策略
        price_policy_qs = models.PricePolicy.objects.filter(category=0, title='个人免费版').first()
        models.Transaction.objects.create(
            status=1,
            # 通过uuid生成随机字符串，赋值给order字段
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=price_policy_qs,
            price=0,
            count=0,
            start_datetime=datetime.datetime.now()
        )

        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'errors': form.errors})


"""
        # 判断用户名是否重复
        user_exist = models.Account.objects.filter(username=form.cleaned_data['username']).exists()
        # 判断手机号是否重复
        phone_exist = models.Account.objects.filter(phone=form.cleaned_data['phone']).exists()
        if user_exist:
            form.add_error('username', '用户名已存在!')
            return render(request, 'register.html', {'form': form})
        if phone_exist:
            form.add_error('phone', '手机号已存在!')
            return render(request, 'register.html', {'form': form})
        inputcode = form.cleaned_data['code']
        conn = get_redis_connection('default')
        cache_code = conn.get(form.cleaned_data['phone'])
        # 判断redis中是否能取到值，避免decode()报错
        if cache_code:
            if cache_code.decode() == inputcode:
                form.save()
                return HttpResponse('成功了！')
        form.add_error('code', '验证码错误!')
        return render(request, 'register.html', {'form': form})
"""


def login_sms(request):
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSmsForm(data=request.POST)
    if form.is_valid():
        request.session['info'] = form.cleaned_data['phone'].id
        request.session.set_expiry(60*60*4)
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'errors': form.errors})


def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        request.session['info'] = form.cleaned_data['username'].id
        request.session.set_expiry(60*60*4)
        return redirect('/index/')
    return render(request, 'login.html', {'form': form})


def img_code(request):
    img, code_string = check_code()
    # 将验证码文本存入session
    request.session['imgCode'] = code_string
    # 设置session过期事件为60s
    request.session.set_expiry(60)
    # 实例化类文件对象
    stream = BytesIO()
    # 将img比特流存入类文件对象
    img.save(stream, 'png')
    return HttpResponse(content=stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('/login/')

